import React, { Fragment } from 'react';
import { Form, Input, DatePicker, Table } from 'antd';
import { history } from 'umi'
import { Pagination, AdvancedSearch } from '@/components';
import moment from 'moment';
import { CopyText } from '@/pages/Task/components';
// import { getDisplayText } from '@/utils/dataDictUtil';
import CompanyDepart from '@/components/CompanyDepart';
import { connect } from 'umi';
import { getUserOrgInfo } from '@/utils/utils';
import { PageFromType } from '@/pages/Task/utils';
import { useEstimatedTaskList } from '../../../hooks';
import { AssessmentModal } from '../../../components';
import { getFormatDateCondition, refreshTaskCount } from '../../../utils';
import styles from '../index.less';

const { RangePicker } = DatePicker;
// 待估算
const PendingAudit = ({ form, location, dispatch }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { query: urlQuery } = location;
    const { firstCompanyCode } = getUserOrgInfo();
    const [modalType, setModalType] = React.useState('');

    const [query, setQuery] = React.useState({
        taskNo: urlQuery.taskNo || '',
        taskName: urlQuery.taskName || '',
        taskExecutor: urlQuery.taskExecutor || '',
        startTime: urlQuery.startTime || '',
        endTime: urlQuery.endTime || '',
        orderByField: urlQuery.orderByField || '',
        pageNo: urlQuery.pageNo || 1,
        pageSize: urlQuery.pageSize || 10,
        executorCompanyCode: urlQuery.executorCompanyCode || firstCompanyCode,
        executorDepartmentCode: urlQuery.executorDepartmentCode || '',
        estimationStateList: [1, 4]
    });
    // 弹窗显示与否
    const [modalVisible, setModalVisible] = React.useState(false);
    const [list, setList] = React.useState('');

    // 更新url及query
    const routerReplace = newQuery => {
        history.push({
            query: {
                ...urlQuery,
                ...newQuery
            }
        });
        setQuery({
            ...query,
            ...newQuery
        });
    };
    // 分页操作
    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        routerReplace({
            ...rest,
            pageNo: current
        });
    };
    const handleTableChange = async (pagination, filters, sorter) => {
        let orderByField = '';
        if (sorter && sorter.field && sorter.order) {
            orderByField = `${sorter.field}|${sorter.order.replace('end', '')}`;
        }
        routerReplace({
            orderByField,
            pageNo: 1
        });
    };

    const [taskLoading, taskData, taskTotal] = useEstimatedTaskList(query);

    const defaultSort = type => {
        const { orderByField = '' } = urlQuery;
        const str = orderByField ? orderByField.replace(`${type}|`, '').trim() : '';
        if (str === 'asc') {
            return 'ascend';
        }
        if (str === 'desc') {
            return 'descend';
        }
        return false;
    };

    // 估算or重估
    const handleActionYes = (record, type) => {
        console.log('handleActionYes -> record', record);
        setModalType(type);
        setList(record);
        setModalVisible(true);
    };

    const columns = [
        {
            title: '任务编号',
            dataIndex: 'taskNo',
            width: 150,
            render: text => <CopyText text={text} />
        },
        {
            title: '任务名称',
            dataIndex: 'taskName',
            render: text => (
                <div
                    style={{
                        width: '100%',
                        minWidth: 200,
                        position: 'relative'
                    }}
                >
                    <span
                        style={{
                            position: 'absolute',
                            left: 0,
                            right: 0,
                            top: 0,
                            transform: 'translateY(-50%)',
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis'
                        }}
                        title={text}
                    >
                        {text}
                    </span>
                </div>
            )
        },
        {
            title: '执行人',
            dataIndex: 'taskExecutor',
            width: 100
        },
        {
            title: '所属部门',
            dataIndex: 'executorDepartmentName'
        },
        // {
        //     title: '优先级',
        //     dataIndex: 'taskPriority',
        //     filters: TaskPriorityList,
        //     width: 115,
        //     filteredValue: typeof query.taskPriority === 'number' ? [query.taskPriority] : [],
        //     filterMultiple: false,
        //     filterDropdown: filterProps => <TableFilter {...filterProps} />,
        //     render: value => getDisplayText(TaskPriorityList, value)
        // },
        {
            title: '发起估算时间',
            dataIndex: 'createTime',
            width: 150,
            sorter: () => {},
            sortOrder: defaultSort('createTime'),
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '')
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 160,
            fixed: 'right',
            className: styles.tableAction,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (_, record) => (
                <React.Fragment>
                    {record.estimationState === 1 ? (
                        <a
                            onClick={() => {
                                handleActionYes(record, 'estimate');
                            }}
                        >
                            估算
                        </a>
                    ) : null}
                    {record.estimationState === 4 ? (
                        <a
                            onClick={() => {
                                handleActionYes(record, 'reCalculate');
                            }}
                        >
                            重估
                        </a>
                    ) : null}
                </React.Fragment>
            )
        }
    ];

    const getParams = () => {
        const param = getFieldsValue();
        const { createTime, gongsi, ...rest } = param;
        const [startTime, endTime] = getFormatDateCondition(createTime);
        const { companyId, departmentId } = gongsi;
        return {
            ...rest,
            startTime,
            endTime,
            executorCompanyCode: companyId,
            executorDepartmentCode: departmentId
        };
    };

    const handleSubmit = () => {
        routerReplace({
            ...getParams(),
            pageNo: 1
        });
    };

    const handelReset = () => {
        handleSubmit();
    };
    const handelOk = () => {
        handleSubmit();
        refreshTaskCount(dispatch);
    };

    React.useEffect(() => {
        const {
            taskNo,
            taskName,
            taskExecutor,
            startTime,
            endTime,
            executorCompanyCode,
            executorDepartmentCode
        } = query;
        form.setFieldsValue({
            taskNo: taskNo || '',
            taskName: taskName || '',
            taskExecutor: taskExecutor || '',
            createTime: startTime && endTime ? [moment(startTime), moment(endTime)] : [],
            gongsi: {
                companyId: executorCompanyCode || firstCompanyCode,
                departmentId: executorDepartmentCode || undefined
            }
        });
    }, []);

    const initCompanyDepart = query.executorCompanyCode ? { companyId: query.executorCompanyCode } : undefined;

    return (
        <Fragment>
            <AdvancedSearch form={form} onSubmit={handleSubmit} onReset={handelReset}>
                <Form.Item label="任务编号">
                    {getFieldDecorator('taskNo', {
                        initialValue: ''
                    })(<Input placeholder="请输入任务编号" allowClear />)}
                </Form.Item>
                <Form.Item label="任务名称">
                    {getFieldDecorator('taskName', {
                        initialValue: ''
                    })(<Input placeholder="请输入任务名称" allowClear />)}
                </Form.Item>
                <Form.Item label="执行人">
                    {getFieldDecorator('taskExecutor', {
                        initialValue: ''
                    })(<Input placeholder="请输入执行人" allowClear />)}
                </Form.Item>
                <Form.Item label="发起估算时间">
                    {getFieldDecorator('createTime', {
                        initialValue: []
                    })(
                        <RangePicker
                            dropdownClassName={styles.rangePicker}
                            ranges={{
                                本周: [moment().startOf('week'), moment().endOf('week')],
                                本月: [moment().startOf('month'), moment().endOf('month')],
                                本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="所属部门">
                    {getFieldDecorator('gongsi', { initialValue: initCompanyDepart })(
                        <CompanyDepart
                            needPermission={false}
                            wrapStyle={{
                                display: 'flex',
                                height: 40,
                                alignItems: 'center'
                            }}
                            companyProps={{ placeholder: '请选择公司' }}
                            departmentProps={{ placeholder: '请选择部门' }}
                            permissionCode={null}
                            // onChange={handelCompanyType}
                        />
                    )}
                </Form.Item>
            </AdvancedSearch>
            <Table
                rowKey="id"
                rowClassName={styles.tableRow}
                bordered={false}
                columns={columns}
                loading={taskLoading}
                dataSource={taskData}
                onChange={handleTableChange}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onRow={record => ({
                    onClick: () => {
                        history.push({
                            pathname: '/work/task/taskdetail',
                            query: {
                                id: record.taskId || '',
                                activeKey: 'assessmentRec',
                                type: PageFromType.RECKON,
                                estimationState: record.estimationState,
                                taskNo: record.taskNo
                            },
                            state: { tabRoute: true, tabRefresh: true }
                        });
                    }
                })}
            />
            <Pagination
                total={taskTotal}
                current={Number(query.pageNo)}
                pageSize={Number(query.pageSize)}
                onChange={handlePaginationChange}
                loading={taskLoading}
            />
            <AssessmentModal
                visible={modalVisible}
                setVisible={setModalVisible}
                list={list}
                onOk={handelOk}
                modalType={modalType}
            />
        </Fragment>
    );
};
export default connect()(Form.create()(PendingAudit));
